package com.weiyu.hbase.impl;

import com.weiyu.hbase.api.HbaseService;
import com.weiyu.hbase.config.HbaseConfig;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class HbaseServiceImpl implements HbaseService {

    @Autowired
    private HbaseConfig con;

    public Connection connection;

    @Override
    public String getValue(String tableName, String rowkey, String family, String column) {
        return null;
    }

    @Override
    public String scanAllRecord(String tablename) throws IOException {
        String record = "";
        TableName name=TableName.valueOf(tablename);
        connection = getConnection();
        Table table = connection.getTable(name);
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        try {
            for(Result result : scanner){
                for (Cell cell : result.rawCells()) {
                    StringBuffer stringBuffer = new StringBuffer().append(Bytes.toString(cell.getRow())).append("\t")
                            .append(Bytes.toString(cell.getFamily())).append("\t")
                            .append(Bytes.toString(cell.getQualifier())).append("\t")
                            .append(Bytes.toString(cell.getValue())).append("\n");
                    String str = stringBuffer.toString();
                    record += str;
                }
            }
        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }

        return record;
    }

    Connection getConnection(){
          try {
              connection = ConnectionFactory.createConnection(con.configuration());
          } catch (IOException e) {
              e.printStackTrace();
          }
          return connection;
      }
}
